package s3;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhangtao
 * @create 2022/4/27 11:27
 */
@Slf4j
@Data
public class S3Util {
    //    @Autowired
    private AmazonS3 amazonS3;

    //    @Value("${s3.bucketName}")
    private String bucketName;

    /**
     * description: 上传文件
     *
     * @param multipartFile
     */
    public String upload(MultipartFile multipartFile) {
        String fileName = multipartFile.getName();
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(multipartFile.getSize());
            amazonS3.putObject(bucketName, fileName, multipartFile.getInputStream(), objectMetadata);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return fileName;
    }

    /**
     * 下载
     *
     * @param objectName 文件对象名称
     * @param fileName   文件名称
     * @param response   响应
     */
//    public void download(String objectName, String fileName, HttpServletResponse response) {
//        InputStream in = null;
//        try {
//            S3Object fileObject = amazonS3.getObject(bucketName, objectName);
//            in = fileObject.getObjectContent();
//            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//            IOUtils.copy(in, response.getOutputStream());
//        } catch (Exception e) {
//            log.error(e.getMessage());
//        } finally {
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                    log.error(e.getMessage());
//                }
//            }
//        }
//    }

    /**
     * description: 判断bucket是否存在，不存在则创建
     *
     * @return: void
     */
    public void existBucket(String bucketName) {
        try {
            boolean exists = amazonS3.doesBucketExistV2(bucketName);
            if (!exists) {
                amazonS3.createBucket(bucketName);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 创建存储bucket
     *
     * @param bucketName 存储bucket名称
     * @return Boolean
     */
    public Boolean createBucket(String bucketName) {
        try {
            amazonS3.createBucket(bucketName);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }


    public void upload(String filePath) {
        // 要上传的文件
        File file = new File(filePath);
        String keyName = file.getName();
        long contentLength = file.length();
        long partSize = 5 * 1024 * 1024; // 设置分片大小为5MB

        List<PartETag> partETags = new ArrayList<>();

        // 初始化分片上传
        InitiateMultipartUploadRequest initRequest = new InitiateMultipartUploadRequest(bucketName, keyName);
        InitiateMultipartUploadResult initResponse = amazonS3.initiateMultipartUpload(initRequest);

        // 上传分片
        long filePosition = 0;
        for (int i = 1; filePosition < contentLength; i++) {
            partSize = Math.min(partSize, (contentLength - filePosition));

            // 分片上传请求
            UploadPartRequest uploadRequest = new UploadPartRequest()
                    .withBucketName(bucketName)
                    .withKey(keyName)
                    .withUploadId(initResponse.getUploadId())
                    .withPartNumber(i)
                    .withFileOffset(filePosition)
                    .withFile(file)
                    .withPartSize(partSize);

            UploadPartResult uploadResult = amazonS3.uploadPart(uploadRequest);
            partETags.add(uploadResult.getPartETag());

            filePosition += partSize;
        }
        // 完成分片上传，object可见
        CompleteMultipartUploadRequest compRequest = new CompleteMultipartUploadRequest(bucketName, keyName,
                initResponse.getUploadId(), partETags);
        amazonS3.completeMultipartUpload(compRequest);
    }

    public List<S3ObjectSummary> getAllObjectsByPrefix(String bucketName, String prefix,
                                                       boolean recursive) {
        ObjectListing objectListing = amazonS3.listObjects(bucketName, prefix);
        return new ArrayList<>(objectListing.getObjectSummaries());
    }

}
